package 数据结构.stack;

import java.util.Scanner;

public class ArrayStackDemo {
    public static void main(String[] args) {
        //测试栈是否成功
        ArrayStack stack = new ArrayStack(4);
        String key = "";
        boolean loop = true;//控制是否退出菜单
        Scanner scanner = new Scanner(System.in);

        while (loop) {
            System.out.println("show:表示显示栈");
            System.out.println("exit:退出程序");
            System.out.println("push:添加数据(入栈)");
            System.out.println("pop:取出数据(出栈)");
            System.out.println("请输入你的选择");
            key = scanner.next();
            switch (key) {
                case "show":
                    stack.list();
                    break;
                case "push":
                    System.out.println("请输入需要的数字");
                    int value = scanner.nextInt();
                    stack.push(value);
                    break;
                case "pop":

                    try {
                        int pop = stack.pop();
                        System.out.println("出栈的数据是:" + pop);
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    break;
                case "exit":
                    scanner.close();
                    loop = false;
                    break;
                default:
                    break;

            }

        }
        System.out.println("程序退出...");
    }
}

class ArrayStack {
    private int maxSize;
    private int[] stack;
    private int top = -1;//表示栈顶

    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        stack = new int[maxSize];
    }

    public boolean ifFull() {
        return top == maxSize - 1;
    }

    public boolean ifEmpty() {
        return top == -1;
    }

    public void push(int value) {
        if (ifFull()) {
            System.out.println("栈满了");
            return;

        }
        top++;
        stack[top] = value;
    }

    //出栈
    public int pop() {
        if (ifEmpty()) {
            throw new RuntimeException("栈空,没有数据");
        }
        int value = stack[top];
        top--;
        return value;
    }

    //遍历栈,需要从栈顶开始显示数据
    public void list() {
        if (ifEmpty()) {
            System.out.println("栈空,没有数据");
            return;
        }
        for (int i = top; i >= 0; i--) {
            System.out.printf("stack[%d]=%d\n", i, stack[i]);
        }

    }
}
